<template>
  <div class="page-main" v-title data-title="标准样批量管理">
    <a-spin :spinning="spinning" >
      <div class="floatNavLeft">
        <a-button  :loading="btnLoading" type="primary" v-show="isEdit && !!stdSampleInfo.id && !currentTaskEdit"  @click="onSubmitForm">提交审批</a-button>
        <a-button  :loading="btnLoading" @click="delForm"   type="danger" v-show="isEdit && !!stdSampleInfo.id ">删除标准</a-button>
          
      </div>   
    <div class="container" ref="imageWrapper">
      <div class="head-content">
        <span class="bold-font">标准样批量管理</span>
        <div class="btn-line">
          <a-button class="hte-btn"  v-show="isEdit" :loading="btnLoading" @click="save">导入</a-button>
          <a-button class="hte-btn add-btn" :loading="btnLoading" type="primary" v-show="isEdit && !!stdSampleInfo.id && !currentTaskEdit"  @click="onSubmitForm">提交审批</a-button>
          <a-button class="hte-btn del-btn" :loading="btnLoading"  type="danger" @click="delForm" v-show="isEdit && !!stdSampleInfo.id">删除标准</a-button>
        </div>
       
      </div>
      <div class="fixed-menu std-menu" style="top:99px;"  v-show="false">
    
        <div  class="functionMould" style="background-color: #ffffff" @click="handAction('his')">
          <a-icon type="history" class="menu-icon" />
          <span> 历史版本</span>
        </div>
      </div>
      <div class="content mt20">
        <a-form-model ref="ruleForm" :model="stdSampleInfo" :rules="rules" :label-col="{ span: 5 }">
          <section>
            <div class="section-header">基本信息
            </div>   
            <a-row :gutter="24">
              <a-col :span="8">
                  <a-form-model-item label="批量编号"   >
                      <a-input v-model="stdSampleInfo.stdNo" disabled placeholder="系统自动生成"/>
                  </a-form-model-item>                
                </a-col> 
              <a-col :span="8">
                  <a-form-model-item label="状态"   >
                      <span>{{stdSampleInfo.status | stdSampleStatusFilter}}</span>
                  </a-form-model-item>                
                </a-col> 
                <a-col :span="8">
                <a-form-model-item  label="提交时间">
                  <a-input v-model="stdSampleInfo.submitTime" disabled placeholder="系统自动生成"/>
                </a-form-model-item>
              </a-col>
            </a-row>        
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="编制部门">
                  <a-input v-model="stdSampleInfo.editDep" disabled placeholder="系统自动生成"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item  label="编制人">
                  <a-input disabled placeholder="系统自动生成" v-model="stdSampleInfo.createUser" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item  label="发布时间">
                  <a-input v-model="stdSampleInfo.pushTime" disabled placeholder="系统自动生成"/>
                </a-form-model-item>
              </a-col>
            </a-row>
            
          </section>
        </a-form-model>
        <section>
          <div class="section-header">
            <span>原标准样内容</span>
           
          </div>
          <div class="section-table">            
            <StdSampleInfoBatchList ref="contentPar"></StdSampleInfoBatchList>

           
          </div>
          
          
        </section>   
        <section>
          <div class="section-header">
            <span>现标准样内容</span>
           
          </div>
          <div class="section-table">       
            <StdSampleInfoBatchList ref="content" @loadData="loadDataParent" :isEdit="isEdit"></StdSampleInfoBatchList>

           
          </div>
          
          
        </section>  
        <section >   
        <template>
              <div class="section-header mt15">
                <div>附件上传<span class="em"></span></div>
              </div>
              <div class="section-table">
                 
                <div class="btn-line"  v-show="!!stdSampleInfo.id">
                  <template>
                    <ht-upload
                      v-if="!!stdSampleInfo.id"
                      ref="myUpload"
                      class="upload-demo"
                      style="margin-left:0"
                      multiple
                      dbKey="Trd"
                      busField="stdAttach"
                      busType=""
                      :busKey="stdSampleInfo.stdSampleBatchId"
                      ftpKey="ftp"
                      v-model="fileData"
                      :show-file-list="false"
                    >
                      <a-button class="hte-btn add-btn" v-if="isEdit && !!stdSampleInfo.id" type="primary" icon="plus">上传</a-button>
                    </ht-upload>                    
                  </template>
                  <a-button class="hte-btn" @click="handAction('download')">下载</a-button>
                  <a-button class="hte-btn" v-if="isEdit"  @click="handAction('delAttach')" >删除</a-button>
                </div>
                <div>
                 <a-tooltip :overlayStyle="{ width: '412px' }" overlayClassName="new-tooltip">
                 
                  <a-table
                    class="hte-table-content"
                    :columns="fileColumns"
                    :data-source="fileData"
                    :pagination="false"
                    :loading="btnLoading"
                    rowKey="id"
                    :row-selection="{ selectedRowKeys: selectedAttachRowKeys, onChange: onSelectAttachChange }"
                    bordered
                    size="middle"
                  >
                  <template slot="fileName" slot-scope="text, record">
                  <template>
                    <a @click="showAttach(record)">{{ record.fileName }}</a>
                  </template>
                </template>
                  </a-table>
                </a-tooltip>
                  
                </div>

              </div>
            </template>  
            </section>   
        <section v-if="processInstanceId&&processInstanceId!=''">
          <div class="section-header">审批意见</div>
          <div class="section-table">
            <template>
              <ht-approval
                ref="childrenRef"
                :process-instance-id="processInstanceId"
                :options="options"
                :custom="custom"
                @reject="afterReject"
                @back="backAction"
                @submit="afterSubmit"
                :before-reject="beforeReject"
                :show-task-history="true"
                :history-dialog="historyDialog"
                :message-id="messageId"
                :showPrintBtn="showPrintBtn"
                :show-upload-btn="true"
                :attach-preview="(file)=>attachPreview(file)"
                :hidden-task-def-key="hiddenTaskDefKey"
                :before-submit="beforeSubmit"
                :taskLoad="taskLoad"
                :snapshotConfigs="snapshotConfigs">
              </ht-approval>
            </template>
          </div>
        </section>
        </div>
        
      </div>

        <process-user-select  :columns="selUserCols" @selectUserConfirm="selectUserConfirm" ref="processUserSelect" />
        <div class="btn-line btn-bottom-fixed">
          <a-button class="hte-btn"   v-show="isEdit" :loading="btnLoading" @click="save">导入</a-button>
          <!-- <a-button class="hte-btn add-btn" type="primary" @click="onSubmitForm" v-show="isEdit && !!stdSampleInfo.id && !currentTaskEdit" :loading="btnLoading">提交审批</a-button>
          <a-button class="hte-btn del-btn" @click="delForm" :loading="btnLoading" v-show="isEdit && !!stdSampleInfo.id">删除</a-button> -->
        </div>

    </a-spin>
      
        
        <LuckSheetPaste :title="'标准样'" downloadKey="标准样模板" ref="luckSheetPaste" :columnsExcel="columnsExcel"  @handleOkExcel="handleOkExcel" ></LuckSheetPaste>
        
  </div>
</template>
<script>
import Vue from 'vue'
import { Modal } from 'ant-design-vue'
import {ACCESS_TOKEN, USER_INFO,USER_NAME} from '@/store/mutation-types'
import '@/config/upload.install.js'
import '@/config/ht-approval.install.js';
import { endWith } from '@/utils/common.js'
import {formatSize, isPreview} from '@/components/hteUpload/common/utils'
import {codeInfoList} from '@/api/codeInfo'
import {getAction,postAction,getActionAsync,previewAttach,deleteAction,postActionAsync} from '@/api/manage'
import { isDateYYYYMMDD,isNumber,isArea,isNumberOrFload } from '@/utils/validate'
import { stdSampleStatusFilter } from '@/utils/filter'
export default {
  name: 'StdSampleInfo',
  components: {
    htApproval: () => import('@/config/ht-approval.umd.min.js'),
    ProcessUserSelect: () => import('@/components/tools/projectBuildStup/ProcessUserSelect'),
    QuestionnaireAuditPage: () => import('@/components/tools/projectBuild/QuestionnaireAuditPage'),
    FixedMenu: () => import('@/components/tools/FixedMenu'),
    StdSampleInfoBatchList: () => import('@/views/library/stdSample/StdSampleInfoBatchList'),
    LuckSheetPaste:()=> import('@/components/excelPaste/LuckSheetPaste'),
    

  },
  mixins: [],
  data() {
    return {
      maraSelectColums:[
          {
            title:'物料编号',
            align:"center",
            dataIndex: 'matnr'
          },
           {
            title:'物料名称',
            align:"center",
            dataIndex: 'maktx'
          }
        ],
        labSelectColums:[
          {
            title:'编码',
            align:"center",
            dataIndex: 'cno'
          },
           {
            title:'实验室全称',
            align:"center",
            dataIndex: 'cname'
          },
          {
            title:'实验室简称',
            align:"center",
            dataIndex: 'cnm'
          }
        ],
        parentStdNoSelectColums:[
           {
            title:'标准样编号',
            align:"center",
            dataIndex: 'stdNo'
          },
          {
            title:'物料编号',
            align:"center",
            dataIndex: 'maraMatnr'
          },
           {
            title:'物料名称',
            align:"center",
            dataIndex: 'maraMaktx'
          }
        ],
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'StdSampleInfo',
      },
      currUser: Vue.ls.get(USER_INFO).username,
      btnShow:false,
      btnLoading:false,
      desLoading:false,
      url:{
        queryBaseById:'/stdSample/queryBaseByIdBatch',
        saveStdSample:'/stdSample/saveStdSample',
        getTree:"/stdSampleType/getTree",
        downLoadBatch:'/common/downLoadBatchWithFileName', // 下载
        delete:'/stdSample/delete',
        submitStdSample:'/stdSample/submitStdSample',
        queryBaseByNo:'/stdSample/queryBaseByNo',
        sapMaraList:'/sapMara/list',
        list:'/stdSample/listBatch',
        labList:'/stdLab/list',
        queryContentQms:'/stdSample/queryContentQms',
        addBatch:'/stdSample/addBatch',
      },      
      sampleBaseId:this.$route.query.sampleBaseId,
      stdSampleInfo: {
       
        sampleContents:[],
        parentSampleContents:[],
      },
      rules: {              
            
        
      },
         
      // 流程引擎
      processInstanceId:'',
      hiddenTaskDefKey:"submit",
      options: {
        request: {
          baseUrl: this.API_BASE_URL,   // 业务系统根路径
          timeOut: 30000,  // 请求超时时间
          interceptors: (config) => {
            config.headers['X-Access-Token']=Vue.ls.get(ACCESS_TOKEN)
            return config
          }
        },
        userId: Vue.ls.get(USER_NAME)
      },
      returnShowConfirm: false,   // 退回显示确认框
      messageId: '',          // 工作台URL里面的msgId参数
      showPrintBtn: false,
      custom: {},
      historyDialog: {}, // 审批历史模态框属性
      snapshotConfigs: [
        {
          type: 'ref',
          value: 'imageWrapper'
        }
      ],
      // 审批人
      selUserCols:[
        // { label: '产品分厂主管', field: 'supervisorUser', username: '', realname: '', required: true,limit:1 },
        // { label: '工艺部主管', field: 'processDepartmentUser', username: '', realname: '', required: true,limit:1 },
        // { label: '质检所/质检部', field: 'qualityDepartmentUser', username: '', realname: '', required: true,limit:1 },
        // { label: '产品研究院分主管', field: 'productDepartmentUser', username: '', realname: '', required: true,limit:1 },
        { label: '相关分厂/工艺研发/质检', field: 'supervisorUser', username: '', realname: '', required: true },
        { label: '质检部主管', field: 'qualityMainDepartmentUser', username: '', realname: '', required: true,limit:1 },
        { label: '产品研究院主管', field: 'productMainDepartmentUser', username: '', realname: '', required: true,limit:1 },
      ],
     
      sampleContents:[],
      parentSampleContents:[],
      // 字典
      dict: {
        orderList0: [], // 准样内容指标
        orderList1: [], // 项目奖励项目类别
      },
      treeData:[],
      spinning:false,
      contentQms: [],
      maraCustomParam:{status:0,maraLikeRightIn:'6,7,8',maraLikeRight:'6'},
      columnsExcel:
      [
        { title: '标准样类型', dataIndex: 'stdMoldName', width: 180, align: 'center' },
        {
          title: '执行日期',
          dataIndex: 'executeTime',
          width: 100,
          align: 'center',
          scopedSlots: { customRender: 'executeTime' },
        },
        { title: '原标准样编号', dataIndex: 'parentStdNo', width: 180, align: 'center' },
        { title: '物料编号', dataIndex: 'maraMatnr', width: 180, align: 'center' },
        { title: '适用物料编号多个英文逗号【,】隔开', dataIndex: 'applyMatnr', width: 180, align: 'center' },
        { title: '质检实验室简称', dataIndex: 'lab', width: 120, align: 'center' },
        { title: '目录分类全称【酱油-原油】', dataIndex: 'stdTypeName', width: 120, align: 'center' },
        { title: '制定/改版的原因', dataIndex: 'reason', width: 120, align: 'center' },
        { title: '标准样变化说明', dataIndex: 'changeReason', width: 120, align: 'center' },
        
        {
          title: '指标编码',
          dataIndex: 'targetCode',
          width: '15%',
          align: 'center',
           scopedSlots: { customRender: 'targetCode' },
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: '25%',
          align: 'center',
           scopedSlots: { customRender: 'remark' },
        },
      
         {
          title: '评级',
          dataIndex: 'grade',
          width: '15%',
          align: 'center',
           scopedSlots: { customRender: 'grade' },
        },        
        {
          title: '评分',
          dataIndex: 'score',
           width: '15%',
          align: 'center',
           scopedSlots: { customRender: 'score' },
        },
        {
          title: '缺陷说明',
          dataIndex: 'defectDesc',
           width: '15%',
          align: 'center',
           scopedSlots: { customRender: 'defectDesc' },
        },
      ],
      currentTaskEdit:false,
      fileColumns: [
        {title: '附件名称',dataIndex: 'fileName',scopedSlots: { customRender: 'fileName' }},
        {title: '文件大小',dataIndex: 'size',width: 150,align: 'center',customRender:function (text) {return formatSize(text)}},
        {title: '上传人',dataIndex: 'uploaderName',width: 150,align: 'center',},
        {title: '上传时间',dataIndex: 'uploadTime',width: 230,align: 'center',},        
      ],
      fileData: [],
      selectedAttachRowKeys:[],    
    }
  },
   filters: {
    stdSampleStatusFilter,
  },
  created(){
    this.initSelectData(); // 查询字典
    
  },
  mounted(){

    this.getStdSampleInfo()
  },

   watch:{
      
    },
    computed:{
    isEdit(){
      return !this.sampleBaseId || (this.stdSampleInfo.status==1 && this.stdSampleInfo.createUserId==this.currUser)
      || (this.stdSampleInfo.status==2 && this.currentTaskEdit)
    },
    
  
  },
 
  methods: {
    /**
     * 初始查询 
     */
   getStdSampleInfo(){
    let that = this
    this.sampleContents = []  
    let sampleContents = []
   
   
     this.btnLoading=true;
    getAction(this.url.queryBaseById,{sampleBaseId:this.sampleBaseId}).then( res=>{
          if(res.code== 200){
             this.stdSampleInfo =  res.result || {sampleContents:[],parentSampleContents:[]}
             this.processInstanceId = this.stdSampleInfo.processInstanceId
             let stdSampleBatchId = this.stdSampleInfo.stdSampleBatchId
             that.$refs.content.customParam = Object.assign(that.$refs.content.customParam,{batchQueryType:'2',stdSampleBatchId:stdSampleBatchId,createType:'2'})
             that.$refs.contentPar.customParam = Object.assign(that.$refs.contentPar.customParam,{batchQueryType:'3',parentStdSampleBatchId: stdSampleBatchId})
             that.$refs.content.loadData()
             that.$refs.contentPar.loadData()
          }else{
            this.$message.warning(res.message)
          }
        }).finally(res=>{
           this.btnLoading=false;
        })
   },
   loadDataParent(){
      let that = this
      that.$refs.contentPar.customParam = Object.assign(that.$refs.contentPar.customParam,{batchQueryType:'3',parentStdSampleBatchId: this.stdSampleInfo.stdSampleBatchId})
      
      that.$refs.contentPar.loadData()
   },
    loadDataNow(arg){
      if (arg === 1) {
                this.ipagination.current = 1;
        }
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
            if (res.success) {
                //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
                this.dataSource = res.result.records || res.result;
                if (res.result.total) {
                    this.ipagination.total = res.result.total;
                } else {
                    this.ipagination.total = 0;
                }
                

            }
            if (res.code === 510) {
                this.$message.warning(res.message)
            }
            this.loading = false;
        })
    },
    initSelectData() {
      const list = []
      list.forEach((item, index)=>{
        codeInfoList({type:item, pageSize:-1,isdel: 0, column:"code",order:"Asc"}).then((res) => {
          if (res.code == 200) {
            this.dict['orderList'+ index] = res.result.records   
             if(index == 0){
             }        
          } else {
            this.$message.warning('查询字典异常:' + res.message)
          }
        })
      })      
    },
     queryContentQms(){
    this.contentQms  = []
    this.sampleContents = []  
    // if(!this.stdSampleInfo.labCode) {
    //   return
    // }
   let ciniSmp = this.stdSampleInfo.labCode.split(',')[0]

   postAction(this.url.queryContentQms,{}).then(res=>{
      if (res.code == 200) {
        let content = res.result  || {vtCodes:[]}
          let contentQms = content.vtCodes.map(item=>{
          let codesSnapshot = item.codes || []
          codesSnapshot = JSON.stringify(codesSnapshot)
          return {target:item.vtdesc ,targetCode:item.verwmerkm,qmsTargetCode:item.verwmerkm,codes:item.codes,codesSnapshot: codesSnapshot,selectSet:item.selectSet}
        })
        this.contentQms = contentQms
        let contentArr = []
        contentQms.forEach(item=>{
            let content = this.stdSampleInfo.sampleContents.find(content=>{return content.targetCode == item.targetCode})
            if(!!content){
                content.qmsTargetCode = item.qmsTargetCode
                content.target = item.target
                content.codes = item.codes
                content.codesSnapshot = item.codesSnapshot
                content.selectSet= item.selectSet
                contentArr.push(content)
            }else{
                contentArr.push(item)    
            }
          })
          this.sampleContents = contentArr
      } else {
        this.$message.warning('查询标准样内容异常:' + res.message)
      }

   })
      
     
    },
    /**
     * 保存
     */
    
    getSaveParams(){
      this.sampleContents.forEach(item=>{

        item.score = !!item.score?item.score:0
        item.gradeCode = !!item.gradeCode?item.gradeCode:''
      })
      this.stdSampleInfo.sampleContents =  this.sampleContents
      this.stdSampleInfo.parentSampleContents =  this.parentSampleContents
      return this.stdSampleInfo
    },
    queryBaseByNo(){
        this.parentSampleContents = []
         getAction(this.url.queryBaseByNo,{stdNo:!this.stdSampleInfo.parentStdNo?'':this.stdSampleInfo.parentStdNo}).then(res=>{
          if(res.code== 200){
             let result = res.result || {sampleContents:[]}
             this.parentSampleContents = result.sampleContents || []
          }else{
            this.$message.warning(res.message)
          }
        }).finally(res=>{

        })
    },
    
   
    handleEmpty(type){
      if(!this.isEdit){return}
      if(type == 'parentStdNo'){
        this.$set(this.stdSampleInfo,'parentStdNo','')
        this.parentSampleContents = [] 
      }
    },
    setStdType(){

      // if(!!this.stdSampleInfo.stdType){return}
      getAction(this.url.list,{maraMatnr:this.stdSampleInfo.maraMatnr,currentDataVersion:1,scopeFlag:false,pageSize:1,column:'t.push_time',order:'Desc'}).then(res=>{
          if(res.code== 200){
             let records = res.result.records || []
             if(records && records.length > 0){
             this.$set(this.stdSampleInfo,'stdType',records[0].stdType)
             }else{
              this.$set(this.stdSampleInfo,'stdType',null)
             }
          }else{
            this.$message.warning(res.message)
          }
        }).finally(res=>{

        })
    },
    /**
     * 提交审批 
     */
    onSubmitForm() {
      let vm=this;
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if(vm.$refs.content.dataSource.length==0){
            vm.$message.warning('请导入数据')
            return
          }
          vm.$refs.processUserSelect.doSelect();
        } else {
          return false;
        }
      });
    },
    delForm(){
    const that = this
      Modal.confirm({
          title: `请确认是否删除?`,          
          onOk: function() {
           deleteAction(that.url.delete, {id:that.stdSampleInfo.id})
            .then((res) => {
              if (res.code == 200) {
                that.$message.success('删除失败成功')
                window.CloseCefTab ? window.CloseCefTab():window.close()
              } else {
                that.$message.warning('删除失败:' + res.message)
              }
            })
            .catch((res) => {
              that.$message.warning('删除失败:' + res.message)
            })
          }
        });
      
    },
   
    selectUserConfirm(cols){
      if(!cols||cols.length===0){
        this.$message.warning('没有选择审批人');
        return;
      }
      let data = {};
      cols.forEach((item) => {
        data[item.field] = item.username
      });
      let stdSampleInfo = this.getSaveParams()
      stdSampleInfo.approvalPerson = data;
      this.spinning = true
      this.btnLoading = true
      //参数组装完毕，发起流程
      postAction(this.url.submitStdSample, stdSampleInfo)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('发起审批流程成功')
            this.getStdSampleInfo();
          } else {
            this.$message.warning('发起流程失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('发起流程异常:' + res.message)
        }).finally(()=>{
          this.spinning = false
          this.btnLoading = false
        })
    }, 

    //-------------流程回调------start
    beforeReject (res) {
      // 驳回前置动作
      return this.checkOptionValue();
    },
    afterReject (res) {
      // 用户点击驳回后成功返回后的处理
      this.getStdSampleInfo();
    },
    backAction (res) {
      this.getStdSampleInfo();
    },
    beforeSubmit(){
      this.currentTaskEdit = false
      this.spinning = true
      return true
    },
    afterSubmit (res) {
          // 用户点击提交后成功返回后的处理
          this.spinning = false
      this.getStdSampleInfo();
    },
    taskLoad(task){
      if(task.taskDefKey === 'submitPublish') {
        this.currentTaskEdit = this.currUser == this.stdSampleInfo.submitUserId
           
      }
    },
    checkOptionValue() {
      let options = this.$refs.childrenRef.data;
      if (options == '' || options == null || options == undefined) {
        this.$message.warning("审批意见不能为空", 3000);
        return false;
      } else {
        return true;
      }
    },
    attachPreview(file,dbKey='Trd') {
      if(dbKey == 'Sac' && this.stdSampleInfo.allAuditors.indexOf(this.currUser)<0&&this.stdSampleInfo.createUserId!==this.currUser){
        this.$message.warning("只有审批人和奖励申请单创建人才可查看附件", 3000);
        return;
      }

      let params={
        id:file.id,
        dbKey:dbKey
      };
      previewAttach(params,'/common/previewAttachProcess').then(result=>{
        const url=URL.createObjectURL(result)
        window.open(process.env.BASE_URL+'/pdf/web/viewer.html?file=' + url)
      }).catch(err => {
        this.$message.warning('下载文件失败');
      })
    },
    //-------------流程回调------end
  
   
    handleChange(type){
    },
    
      handAction(type,record,index){      
        let that = this
        if(type == 'download'){
        // 下载
        if(this.selectedAttachRowKeys.length == 0){
          this.$message.warning('请选择至少一条数据！');
          return;
        }
        let attachIds=this.selectedAttachRowKeys.join(",");
        this.doDownLoadBatch(attachIds);
      }
     
      if(type == 'delAttach'){
        // 删除        
        if(this.selectedAttachRowKeys.length == 0){
          this.$message.warning('请选择至少一条数据！');
          return;
        }
        const that = this;
     
        Modal.confirm({
          title: '请确认是否删除此附件?',          
          onOk: function() {
            for (let i = that.selectedAttachRowKeys.length - 1; i > -1; i--) {
              const id = that.selectedAttachRowKeys[i] ;
              const obj = {id,dbKey:'Trd',ftpKey:'ftp'}
              that.$refs['myUpload'].delete(obj);
            }  
            that.selectedAttachRowKeys = []
          }
        });
      }
      if(type =='his'){
          this.gotoDetail(`/stdSample/hisList/${this.stdSampleInfo.stdSampleId}/${this.stdSampleInfo.id}`)
      }
      
    },
     gotoDetail(url) {
      let routeUrl = this.$router.resolve({
        path: url,
      })
      window.open(routeUrl.href, '_blank')
    },
     doDownLoadBatch(attachIds) {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame');
      iframe.src = this.API_BASE_URL +
        this.url.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=ftp&token=' +
        Vue.ls.get(ACCESS_TOKEN)+'&zipFileName='+encodeURIComponent(this.stdSampleInfo.stdNo+'附件.zip');
    },
    save(){
        this.$refs.luckSheetPaste.showModalExcel();
      },
    handleOkExcel(data,excelVm){
        let groupMap = new Map()
        let baseVos = []
        for (let index = 0; index < data.length; index++) {
          let rowIndex = index + 1
          const element = data[index];
          
          
          if(!element.stdMoldName){
             excelVm.handleErroMsg(`第${rowIndex}行标准样类型必填！`)
            return 
          }
          if(element.stdMoldName=='制定'){
            element.stdMold = '1'
          }else{
            element.stdMold = '2'
          }
          if(!element.executeTime || !isDateYYYYMMDD(element.executeTime)){
             excelVm.handleErroMsg(`第${rowIndex}行执行日期必填，日期格式出错！`)
            return 
          }
         
          if(!element.maraMatnr){
             excelVm.handleErroMsg(`第${rowIndex}行物料编号必填！`)
            return 
          }
          if(!element.maraMatnr){
             excelVm.handleErroMsg(`第${rowIndex}行物料编号必填！`)
            return 
          }
          if(!element.lab){
             excelVm.handleErroMsg(`第${rowIndex}行质检实验室必填！`)
            return 
          }

          if(!element.stdTypeName){
             excelVm.handleErroMsg(`第${rowIndex}行目录分类必填！`)
            return 
          }
          if(!element.reason || element.reason.length > 500){
             excelVm.handleErroMsg(`第${rowIndex}行制定/改版的原因必填,长度控制500字以内！`)
             return 
          }
          if(!!element.changeReason && element.changeReason.length > 500){
             excelVm.handleErroMsg(`第${rowIndex}行标准样变化说明,长度控制500字以内！`)
             return 
          }
          if(!element.targetCode){
             excelVm.handleErroMsg(`第${rowIndex}行指标编码必填！`)
             return 
          }

          if(!element.remark || element.remark.length > 500){
             excelVm.handleErroMsg(`第${rowIndex}行备注必填,长度控制500字以内！`)
             return 
          }

          if(!element.grade){
             excelVm.handleErroMsg(`第${rowIndex}行评级必填！`)
             return 
          }
          if(!element.score || !isNumberOrFload(element.score,1,1)){
             excelVm.handleErroMsg(`第${rowIndex}行评分必填,评分格式不正确！`)
             return 
          }
          
          if(!!element.defectDesc && element.defectDesc.length>35){
             excelVm.handleErroMsg(`第${rowIndex}行缺陷说明,长度控制35字以内！`)
             return 
          }
          
          let groupItem =   element.stdMold + '' + element.maraMatnr + '' + element.stdTypeName
          element.sampleContents = [{targetCode:element.targetCode,remark:element.remark
            ,grade:element.grade,score:element.score,score:element.score,defectDesc:element.defectDesc
          }] 
          if( !groupMap.has(groupItem) ) {
            groupMap.set(groupItem,element)
          }else{
           let value = groupMap.get(groupItem)
           value.sampleContents = [...value.sampleContents,...element.sampleContents]
           groupMap.set(groupItem,value)
          }
        }
        for (let value of groupMap.values()) {
          baseVos.push(value)
        }  
        postAction(this.url.addBatch,Object.assign(this.stdSampleInfo,{baseVos:baseVos}) ).then(res => {
          
            if(res.code === 200){
              this.$message.success("导入成功");
              excelVm.afterClose()
              this.getStdSampleInfo()
            
            }else{
              excelVm.handleErroMsg('操作异常:'+res.message);
            }
        }).catch(res=>{
            this.excelConfirmLoading = false;
            excelVm.handleErroMsg('操作异常:'+res.message);           
        })
      },
   
    onSelectAttachChange(selectedRowKeys, selectionRows) {
      this.selectedAttachRowKeys = selectedRowKeys
    },
    doDownLoadBatch(attachIds) {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame');
      iframe.src = this.API_BASE_URL +
        this.url.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=ftp&token=' +
        Vue.ls.get(ACCESS_TOKEN)+'&zipFileName='+encodeURIComponent(`标准样${this.stdSampleInfo.stdNo}附件.zip`);
    },
    showAttach(record) {
      var id = record.id
      var fileName = record.fileName
      //以rar、zip、dwg结尾的文件，直接下载不预览
      if (
        endWith(fileName, 'rar') ||
        endWith(fileName, 'zip') ||
        endWith(fileName, 'dwg') ||
        endWith(fileName, 'tgz')
      ) {
        this.$emit('afterDown', [record])
        this.doDownLoadBatch(id)
        return
      }
      let params = {
        id: id,
        ftpKey: 'ftp',
      }
      previewAttach(params)
        .then((result) => {
          const url = URL.createObjectURL(result)
          window.open(process.env.BASE_URL + '/pdf/web/viewer.html?file=' + url)
        })
        .catch((err) => {
          this.$message.warning('下载文件失败')
        })
    },
   
    
   
  }  
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
@import '~@views/library/hteFile.less';
em{margin-left: 5px;}
.mt20{margin-top:20px;}
.btn-span{margin-right: 15px;
  &:last-of-type{margin-right: 0;}
}
/deep/ .mes-box{
  select{width: 200px;margin-left: 10px;}
}
/deep/ .upload-demo{display: inline-block;margin-left: 15px;}
/deep/ #process-container {
  width: unset !important;
}
/deep/ #process-container .process-item .info-fullMessage {
  max-width: 1200px;
}
.floatNavLeft {
  position: fixed;
  top: 180px;
  left: 30px;
  z-index: 1;

  > button {
    display: block;
    margin-bottom: 10px;
  }
}

@media (max-width: 1080px) {


  .floatNavLeft {
    left: 5px;

    > button {
      padding: 0 2px;
      font-size: 12px;
    }
  }
}

</style>
